<!--
 * @Description: 收款单表单弹窗
-->
<template>
  <a-drawer :title="formTitle" :open="visible" @close="onClose">
    <template #closeIcon>
      <div class="express-bar"></div>
      <div class="express-btn">
        <CloseCircleOutlined :size="32" @click="onClose" />
      </div>
    </template>
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 6 }">
      <a-card title="基本信息" class="smart-margin-bottom10">
        <a-row :gutter="{ sm: 8, md: 16, lg: 24 }">
          <a-col :span="21">
            <a-row :gutter="{ xs: 8, sm: 16, md: 24, lg: 32 }">
              <a-col :span="8">
                <a-form-item label="收款类型" name="payee_type">
                  <EnumSelect enum-name="PAYEE_TYPE_ENUM" v-model:value="form.payee_type" @change="handleChange" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="交款人" name="payee_id">
                  <a-select v-model:value="form.payee_id" :options="optionsPayee" placeholder="请选择交款人" @change="onChangePayeeId" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="交款信息类型" name="channel">
                  <a-input v-model:value="form.channel" placeholder="请输入交款信息类型" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="收款金额" name="amount">
                  <a-input v-model:value="form.amount" disabled />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="交易流水号" name="trade_no">
                  <a-input v-model:value="form.trade_no" placeholder="请输入交易流水号" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="备注" name="remark">
                  <a-input v-model:value="form.remark" placeholder="请输入备注" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-col>
          <a-col :span="3">
            <a-col :span="8">
              <a-form-item label="" name="voucher">
                <FileUpload v-model:value="form.voucher" :default-file-list="form.voucher" buttonText="上传凭证" :maxUploadSize="1" :maxSize="1" accept=".jpeg,.jpg,.png" />
              </a-form-item>
            </a-col>
          </a-col>
        </a-row>
      </a-card>
    </a-form>
    <template #footer>
      <div class="smart-table-operate-block">
        <a-button style="margin-right: 8px" @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">提交</a-button>
      </div>
    </template>
  </a-drawer>
</template>
<script setup lang="ts">
import _ from 'lodash'
import { message } from 'ant-design-vue'
import { useLoadingStore } from '@/store/modules/loading-store'
import FileUpload from '@/components/support/file-upload/index.vue'
import { errorSentry } from '@/lib/error-sentry'
import EnumSelect from '@/components/framework/enum-select/index.vue'
import { paymentApi } from '@/api/business/finance/receipt-api'
import { searchApi } from '@/api/search/search-api'

const loadingStore = useLoadingStore()
// emit
const emit = defineEmits(['reload-list'])

// 组件ref
const formRef = ref()

const formDefault = {
  // 收款类型
  payee_type: '',
  // 交款人
  payee_id: '',
  // 交款信息类型
  channel: '',
  // 收款金额
  amount: '',
  // 交易流水号
  trade_no: '',
  // 备注
  remark: '',
  // 凭证
  voucher: ''
}

const form = ref({ ...formDefault })
const rules = {
  payee_type: [{ required: true, message: '请选择收款类型', trigger: 'blur' }],
  payee_id: [{ required: true, message: '请选择交款人', trigger: 'blur' }],
  amount: [{ required: true, message: '请输入收款金额', trigger: 'blur' }],
  trade_no: [{ required: true, message: '请输入交易流水号', trigger: 'blur' }]
}
// 收款类型
const optionsPayee = ref([])
const handleChange = (value: number) => {
  form.value.payee_id = null
  if (value == 1) {
    searchSalesmanList()
  } else {
    searchDriverList()
  }
}
// 业务员
const searchSalesmanList = async () => {
  const res = await searchApi.salesmanList({ fields: 'id,rename' })
  optionsPayee.value = res.data.map((item) => {
    return {
      value: item.id,
      label: item.rename
    }
  })
}
// 司机
const searchDriverList = async () => {
  const res = await searchApi.driverList({ fields: 'id,name' })
  optionsPayee.value = res.data.map((item) => {
    return {
      value: item.id,
      label: item.name
    }
  })
}
//新增交款人获取收款金额
const onChangePayeeId = async (value: number) => {
  const res = await paymentApi.amountPayment({ payee_id: value, payee_type: form.value.payee_type })
  form.value.amount = res.data.amount
}

// 是否展示抽屉
const visible = ref(false)

function showDrawer(rowData) {
  form.value = formDefault
  if (rowData && !_.isEmpty(rowData)) {
    form.value = _.pick(rowData, ['id', ..._.keys(formDefault)])
  }
  visible.value = true
  nextTick(() => {
    formRef.value.clearValidate()
  })
}

function onClose() {
  form.value = formDefault
  visible.value = false
}

function onSubmit() {
  formRef.value
    .validate()
    .then(async () => {
      loadingStore.show()
      try {
        if (unref(form).id) {
          // await dealerApi.update(unref(form));
        } else {
          await paymentApi.addPayment(unref(form))
        }
        message.success('操作成功')
        onClose()
        emit('reload-list')
      } catch (error) {
        message.error(error.msg)
        errorSentry.captureError(error)
      } finally {
        loadingStore.hide()
      }
    })
    .catch((error) => {
      message.error('参数验证错误，请仔细填写表单数据!')
    })
}

defineExpose({
  showDrawer
})

// 表单标题
const formTitle = computed(() => (form.value.id ? '编辑' : '新增'))
</script>
